const db = require('../db/index')
const router = require('../router/upload.js')
const uploadFile = require("../File/file.js");

const upload = async (req, res) => {	//注意，同步要加，否则file不会挂载
  try {
		await uploadFile(req, res);
		if (req.file == undefined) {
		  return res.status(400).send({ message: "请选择要上传的文件" });
		}
	  } catch (err) {
		res.status(500).send({
		  message: `无法上传文件: ${req.file.originalname}. ${err}`,
		});
	  }
// console.log(req.file)
  let laster = req.file.destination.split('/')
  const url = 'http://127.0.0.1:3007/uploads/' + laster[4]+'/'+req.file.originalname
  const temp = {
  	  article_id: 47,
  	  writer_id: 3,
  	  file_url:url
  }
  const sql = 'insert into ev_files set ?'
  
  db.query(sql, temp,(err,results)=>{
	  if(err)
		return res.cc(err);
	  if (results.affectedRows !== 1)
		return res.cc('发布文章失败')
	  res.send({
		  status:200,
		  message:'文件上传成功！',
	  });
  })
};

const getListFiles = (req, res) => {
  const directoryPath = __basedir + "/resources/static/assets/uploads/";
  fs.readdir(directoryPath, function (err, files) {
    if (err) {
      res.status(500).send({
        message: "没有找到文件。",
      });
    }
    let fileInfos = [];
    files.forEach((file) => {
      fileInfos.push({
        name: file,
        url: baseUrl + file,
      });
    });
    res.status(200).send(fileInfos);
  });
};

const download = (req, res) => {
  const fileName = req.params.filename;
  // const directoryPath = __basedir + "/resources/static/assets/uploads/";
  const directoryPath = 'E:/Front_Learn/API_SERVER_1/uploads/'
  res.download(directoryPath + fileName, fileName, (err) => {
    if (err) {
      res.status(500).send({
        message: "无法获取文件。" + err,
      });
    }
  });
};

module.exports = {
  upload,
  getListFiles,
  download,
};